/*
 * Created by JFormDesigner on Sun Aug 22 01:06:03 CST 2021
 */

package com.minelx.statementplus.ui.form.ui;

import com.minelx.landisk.filesystem.Paths;
import com.minelx.landisk.filesystem.core.Directory;
import com.minelx.landisk.filesystem.core.File;
import com.minelx.statementplus.ui.form.swing.DialogInputs;
import com.minelx.table.core.Table;
import com.minelx.table.core.Tables;
import com.minelx.woods.task.core.ChaSessionFactory;
import com.minelx.woods.task.core.SqlTaskService;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.minelx.landisk.filesystem.core.init.OpenPolicy.useExisting;

/**
 * @author aaa
 */
public class TablesForm extends JFrame {
	static {
		try {
			UIManager.setLookAndFeel(new NimbusLookAndFeel());
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new TablesForm().setVisible(true);
	}

	private final DownloadService downloadService;

	private final DefaultListModel<File> tableModel;

	public TablesForm() {
		initComponents();

		tableModel = new DefaultListModel<>();
		tableList.setModel(tableModel);

		SqlTaskService sqlTaskService = new SqlTaskService(ChaSessionFactory.http(), 2, true);
		downloadService = new DownloadService(sqlTaskService, tableModel);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				sqlTaskService.close();
			}
		});
	}

	private void newButtonActionPerformed(ActionEvent e) {
		new AddingTableDialog(this, downloadService, tableModel).setVisible(true);
	}

	private void removeButtonActionPerformed(ActionEvent e) {
		tableModel.removeElementAt(tableList.getSelectedIndex());
	}

	private void clearButtonActionPerformed(ActionEvent e) {
		tableModel.clear();
	}

	private void previewButtonActionPerformed(ActionEvent e) {
		try {
			Table selectedTable = Tables.csv(tableModel.getElementAt(tableList.getSelectedIndex()).read(StandardCharsets.UTF_8));
			new TableDialog(this, selectedTable, downloadService).setVisible(true);
		} catch (IOException exception) {
			exception.printStackTrace();
		}
	}

	private void importFileButtonActionPerformed(ActionEvent e) {
		Directory downloadedFiles = Paths.projectRoot()
				.child().dir("downloaded_files", useExisting());
		List<File> files = downloadedFiles.children()
				.filter(path -> path.getPath().toFile().isFile())
				.map(path -> File.create(path, useExisting()))
				.all();
		String fileName = DialogInputs.chooseOneOf(this, files.stream()
				.map(file -> file.path().getName())
				.toArray(String[]::new), "选择导入文件");
		tableModel.addElement(files.stream()
				.filter(file -> file.path().getName().equals(fileName))
				.findFirst().orElseThrow());
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		panel1 = new JPanel();
		label1 = new JLabel();
		scrollPane1 = new JScrollPane();
		tableList = new JList<>();
		panel2 = new JPanel();
		importFileButton = new JButton();
		newButton = new JButton();
		removeButton = new JButton();
		clearButton = new JButton();
		previewButton = new JButton();

		//======== this ========
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setTitle("\u8d44\u6e90");
		var contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== panel1 ========
		{
			panel1.setBorder(new EmptyBorder(12, 12, 12, 12));
			panel1.setLayout(new BorderLayout(12, 12));

			//---- label1 ----
			label1.setText("\u8d44\u6e90\u5217\u8868: ");
			label1.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
			panel1.add(label1, BorderLayout.NORTH);

			//======== scrollPane1 ========
			{

				//---- tableList ----
				tableList.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 22));
				scrollPane1.setViewportView(tableList);
			}
			panel1.add(scrollPane1, BorderLayout.CENTER);

			//======== panel2 ========
			{
				panel2.setLayout(new FlowLayout(FlowLayout.TRAILING, 10, 0));

				//---- importFileButton ----
				importFileButton.setText("\u5bfc\u5165\u8d44\u6e90");
				importFileButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 20));
				importFileButton.addActionListener(e -> importFileButtonActionPerformed(e));
				panel2.add(importFileButton);

				//---- newButton ----
				newButton.setText("\u4e0b\u8f7d\u8d44\u6e90");
				newButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 20));
				newButton.addActionListener(e -> newButtonActionPerformed(e));
				panel2.add(newButton);

				//---- removeButton ----
				removeButton.setText("\u79fb\u9664");
				removeButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 20));
				removeButton.addActionListener(e -> removeButtonActionPerformed(e));
				panel2.add(removeButton);

				//---- clearButton ----
				clearButton.setText("\u6e05\u7a7a");
				clearButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 20));
				clearButton.addActionListener(e -> clearButtonActionPerformed(e));
				panel2.add(clearButton);

				//---- previewButton ----
				previewButton.setText("\u9884\u89c8");
				previewButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 20));
				previewButton.addActionListener(e -> previewButtonActionPerformed(e));
				panel2.add(previewButton);
			}
			panel1.add(panel2, BorderLayout.SOUTH);
		}
		contentPane.add(panel1, BorderLayout.CENTER);
		setSize(970, 700);
		setLocationRelativeTo(getOwner());
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	private JPanel panel1;
	private JLabel label1;
	private JScrollPane scrollPane1;
	private JList<File> tableList;
	private JPanel panel2;
	private JButton importFileButton;
	private JButton newButton;
	private JButton removeButton;
	private JButton clearButton;
	private JButton previewButton;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
}
